package org.example.qos;

import com.rabbitmq.client.*;
import org.example.exchange.direct.DirectProducer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: anlu
 * @Date: 2021/06/22/15:20
 * @Description: 普通消费者
 */
public class QosConsumerMain {
    public static void main(String[] args)throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");

        //打开连接和创建信道
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        // 定义交换器类型
        channel.exchangeDeclare(DirectProducer.EXCHANGE_NAME,"direct");
        /*声明一个队列*/
        String queueName = "focuserror";
        channel.queueDeclare(queueName,false,false,
                false,null);
        //绑定，将队列和交换器通过路由键进行绑定
        String routeKey = "error";
        channel.queueBind(queueName,DirectProducer.EXCHANGE_NAME,routeKey);
        System.out.println("waiting for message........");
        /*声明了一个消费者*/
        final Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("哈哈Received["+envelope.getRoutingKey()
                        +"]"+message);
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };

        /**
         * channel.basicQos(1)指该消费者在接收到队列里的消息但没有返回确认结果之前,
         * 队列不会将新的消息分发给该消费者。队列中没有被消费的消息不会被删除，还是存在于队列中。
         */
        channel.basicQos(150,true);
        BatchAckConsumer batchAckConsumer = new BatchAckConsumer(channel);
        // 添加默认的消费者
        channel.basicConsume(queueName,false,consumer);
        // 添加批量的消费者
        channel.basicConsume(queueName,false,batchAckConsumer);
    }
}
